<script setup>
import { User, Lock } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { ElMessage } from 'element-plus';
//控制注册与登录表单的显示， 默认显示注册
const isRegister = ref(false)
//定义数据模型
const registerData = ref({
    username: '',
    password: '',
    confirmPassword: ''
})
//
const checkRePassword = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请再次输入密码'))
    } else if (registerData.value.password !== value) {
        callback(new Error('两次输入的密码不一致'))
    } else {
        callback()
    }
}
//表单校验
const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 5, max: 16, message: '长度在 5 到 16 个非空字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 5, max: 16, message: '长度在 5 到 16 个非空字符', trigger: 'blur' }
    ],
    confirmPassword: [
        { validator: checkRePassword, trigger: 'blur' }
    ]
}
//调用后端接口
import { userRegisterService, userLoginService } from '@/api/user.js'
import { useRouter } from 'vue-router'
import { useTokenStore } from '@/stores/token.js';
const tokenStore = useTokenStore();
const router = useRouter()
const register = async () => {

    let result = await userRegisterService(registerData.value);
    // if(result.code===0){
    //     alert(result.msg ? result.msg : '注册成功');
    // }else{
    //     alert('注册失败')
    // }
    ElMessage.success(result.msg ? result.msg : '注册成功');
}
//登录函数
// const login = async () => {
//     try {
//         // 调用登录服务
//         const result = await userLoginService(registerData.value);

//         // 检查登录结果
//         if (result.code === 0) {
//             ElMessage.success(result.msg ? result.msg : "登录成功");

//             // 从返回结果中获取用户角色
//             const userRole = result.data.user.role; // 假设 `role` 是返回数据中的字段
//             console.log(userRole);
//             // 存储 Token
//             tokenStore.setToken(result.data.token); // 假设 `token` 是返回数据中的字段

    //         // 根据角色跳转不同页面
    //         switch (userRole) {
    //             case "0":
    //                 // 跳转到患者首页
    //                 router.push("/patient/home");
    //                 break;
    //             case "1":
    //                 // 跳转到管理员首页
    //                 router.push("/admin/home");
    //                 break;
    //             case "2":
    //                 // 跳转到医生首页
    //                 router.push("/doctor/home");
    //                 break;
    //             default:
    //                 // 默认跳转到首页（可选）
    //                 router.push("/");
    //         }
    //     } else {
    //         ElMessage.error(result.msg ? result.msg : "登录失败，请检查账号或密码");
    //     }
    // } catch (error) {
    //     console.error("登录失败:", error);
    //     ElMessage.error("登录失败，请稍后再试");
    // }
// };
//定义函数清空数据模型数据
const login = async () => {
    try {
        const result = await userLoginService(registerData.value);
        if (result.code === 0) {
            const userRole = result.data.user.role;
            
            // 同时存储 token 和角色
            tokenStore.setToken(result.data.token, userRole);
            
            // 根据角色跳转不同页面
            switch (userRole) {
                case "0":
                    // 跳转到患者首页
                    router.push("/patient");
                    break;
                case "1":
                    // 跳转到管理员首页
                    router.push("/admin");
                    break;
                case "2":
                    // 跳转到医生首页
                    router.push("/doctor");
                    break;
                default:
                    // 默认跳转到首页（可选）
                    router.push("/");
            }
        } else {
            ElMessage.error(result.msg ? result.msg : "登录失败，请检查账号或密码");
        }
    } catch (error) {
        console.error("登录失败:", error);
        ElMessage.error("登录失败，请稍后再试");
    }
};
const clearData = () => {
    registerData.value = {
        username: '',
        password: '',
        confirmPassword: ''
    }
}
</script>

<template>
    <el-row class="login-page">
        
        <!-- <el-col :span="12" class="bg"></el-col> -->
        <el-col :span="6" :offset="9" class="form">
            <!-- 注册表单 -->
            <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="rules">
                <el-form-item>
                    <h1>注册</h1>
                </el-form-item>
                <el-form-item prop="username">
                    <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码"
                        v-model="registerData.password"></el-input>
                </el-form-item>
                <el-form-item prop="confirmPassword">
                    <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码"
                        v-model="registerData.confirmPassword"></el-input>
                </el-form-item>
                <!-- 注册按钮 -->
                <el-form-item>
                    <el-button class="button" type="primary" auto-insert-space @click="register"style="font-size: 18px;">
                        注册
                    </el-button>
                </el-form-item>
                <el-form-item class="flex">
                    <el-link type="info" :underline="false" @click="isRegister = false; clearData()" style="font-size: 18px;">
                        ← 返回
                    </el-link>
                </el-form-item>
            </el-form>
            <!-- 登录表单 -->
            <el-form ref="form" size="large" autocomplete="off" v-else :model="registerData" :rules="rules">
                <el-form-item>
                    <h1>登录</h1>
                </el-form-item>
                <el-form-item prop="username">
                    <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码"
                        v-model="registerData.password"></el-input>
                </el-form-item>
                <el-form-item class="flex">
                    <div class="flex">
                        <el-checkbox>记住我</el-checkbox>
                        <el-link type="primary" :underline="false">忘记密码？</el-link>
                    </div>
                </el-form-item>
                <!-- 登录按钮 -->
                <el-form-item>
                    <el-button class="button" type="primary" auto-insert-space @click="login"style="font-size: 18px;">登录</el-button>
                </el-form-item>
                <el-form-item class="flex">
                    <el-link type="info" :underline="false" @click="isRegister = true; clearData()"style="font-size: 18px;">
                        注册 →
                    </el-link>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
</template>

<style lang="scss" scoped>
/* 样式 */
.login-page {
    height: 100vh;
    background-color: #fff;

    height: 100vh;
  background-image: url("../assets/医生.png"); /* 替换为你的图片路径 */
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat; 

    .form {
        display: flex;
        flex-direction: column;
        justify-content: center;
        user-select: none;

        .title {
            margin: 0 auto;
        }

        .button {
            width: 100%;
        }

        .flex {
            width: 100%;
            display: flex;
            justify-content: space-between;
        }
    }
}

</style>